//Service for setting alarms, and responding to system-broadcasted intents
//Brian Belding
//Governor's School of Engineering and Technology, 2010

//android.permission.BLUETOOTH_ADMIN
/* TODO:
 * [v]Wifi
 * [v]GPS
 * [v]Time Start
 * [v]Time End
 * [v]volume
 * [v]ringermode
 * [v]brightness
 * [v]bluetooth
 * []autoreply sms
 * [v]Day of Week
 * []airplane mode
 * []contact
 */


package edu.govschool2010.services;

import android.app.PendingIntent;

import android.app.Service;
import android.app.AlarmManager;
import android.bluetooth.BluetoothAdapter;
import android.content.*;
import android.location.Location;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.widget.Toast;
import edu.govschool2010.shared.*;
import 	java.util.Calendar;
import java.util.*;


public class DataService extends android.app.Service{
        @Override
        public void onCreate() {
        	super.onCreate();
                /* TODO:
                 * 
            
                 * create ArrayList and populate
                 * Check for existing alarms
                 * if false: set appropriate alarms and intents
                 * 
                 * android.location.LocationManager
				 * public void addProximityAlert (double latitude, double longitude, float radius, -1, PendingIntent intent)
				 * 
				 * Android.app.AlarmManager
				 * public void set (int type, long triggerAtTime, PendingIntent operation)
				 *
                 */
        	Update.registerDataService(this);
        
        	ArrayList <Situation> Array = new ArrayList <Situation>();
        	edu.govschool2010.shared.ReadFromFile.getInstanceR().Read(Array);
       	
  			
  			
        	for (int count = 0; count <= Array.size()-1; count++){
        		if (Array.get(count).gps != null){
        			Location location = Array.get(count).loc;
        			setProx(location.getLatitude(), location.getLongitude(), location.getAccuracy(), Array.get(count).situationName);

        		}
        		if (Array.get(count).startTime != -1){
                	setAlarm(Array.get(count).startTime, Array.get(count).endTime, Array.get(count).situationName);
        		}
        	}
        int duration = Toast.LENGTH_SHORT;
        
        Toast toast = Toast.makeText(this, "Background service started", duration);
        toast.show(); //show a reaction to being called

        	
        }
       

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
                if ((flags & START_FLAG_RETRY) == 0 ){
                        //its a restarted process DO SOMETHING
                        Toast restart = Toast.makeText(this, "Set&Forget restarted by run time", Toast.LENGTH_SHORT);
                        restart.show();
                }
                else{
                        //continue as normal
                }
                return Service.START_STICKY;
        }
        
        
        @Override
        public IBinder onBind(Intent intent) {
        	
                return null;
        }
        
        public void processSituations(List<Situation> sits){
        	//create alarms/alerts
        }
        
        public void setProx (double lat, double lng, float radius, String situation){

			LocationManager LM = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
        	Intent ilocation = new Intent(situation);
        	PendingIntent LocationChange = PendingIntent.getBroadcast(getApplicationContext(), -1, ilocation, 0); 
			LM.addProximityAlert(lat, lng, radius, -1, LocationChange);
        }
        public void setAlarm (long start, long end, String situation){
        	Intent times = new Intent(situation);
        	Intent timee = new Intent(situation);

        	
        	PendingIntent TimeStart = PendingIntent.getBroadcast(getApplicationContext(), -1, times, 0);
        	PendingIntent TimeEnd = PendingIntent.getBroadcast(getApplicationContext(), -1, timee, 0);
			AlarmManager AM = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);
		AM.set(AlarmManager.RTC_WAKEUP, start, TimeStart);
    	AM.set(AlarmManager.RTC_WAKEUP, end, TimeEnd);
        }
 /*     
public class update extends android.content.BroadcastReceiver{

			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub
				checksituations(intent);	
					
				
			}
        	//check situations for entirety
        	//call necessary settings
}
*/
    
		public void checksituations(Intent intent){
			int day = Calendar.DAY_OF_WEEK;

        	ArrayList <Situation> Array = new ArrayList <Situation>();
        	edu.govschool2010.shared.ReadFromFile.getInstanceR().Read(Array);
       	boolean vwifi = false, vringer = false, vbright = false, vairplane = false, vblue = false, vvolume = false;
		LocationManager LM = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
		android.location.Location now = LM.getLastKnownLocation("gps");
		long time = java.lang.System.currentTimeMillis();
		time = time % 86400000;
		for (int count = 0; count < Array.size(); count++){

				float dist = now.distanceTo(Array.get(count).loc);
				if((Array.get(count).daysOfWeek[day] == true || Array.get(count).daysOfWeek == null) && (Array.get(count).startTime == -1 || ((Array.get(count).startTime < time) && (time < Array.get(count).endTime))) && (Array.get(count).gps == null || (dist < Array.get(count).loc.getAccuracy()))){
					if (Array.get(count).airplaneMode != null && vairplane == false){
						airplaneMode(Array.get(count).airplaneMode);
						vairplane = true;
					}
					if (Array.get(count).wifi != null && vwifi == false){
						changeWifi(Array.get(count).wifi);
						vwifi = true;
					}
					if (Array.get(count).bluetooth != null && vblue == false){
						bluetooth(Array.get(count).bluetooth);
						vblue = true;
					}
					if (Array.get(count).ringerMode != null && vringer == false){
						RingerMode(Array.get(count).ringerMode);
						vringer = true;
					}
					if (Array.get(count).brightness != null && vbright == false){
						brightness(Array.get(count).brightness);
						vbright = true;					}
					}
					if (Array.get(count).volume != null && vvolume == false){
						changeVolume(Array.get(count).volume);
						vvolume = true;
					}
			}
			}
        private void RingerMode (int mode){
                AudioManager AM = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
                AM.setRingerMode(mode);
                //RINGER_MODE_NORMAL , RINGER_MODE_SILENT, or RINGER_MODE_VIBRATE.
                //(2, 0, 1, respectively)
                
        }
        private void brightness (String level){
        	ContentResolver cr = getApplicationContext().getContentResolver();
        	android.provider.Settings.System.putString(cr, android.provider.Settings.System.SCREEN_BRIGHTNESS, level);
        }
        private void airplaneMode(boolean enabled){
        	//TODO: configure airplane mode
        }
        private void bluetooth (boolean enabled){

                BluetoothAdapter BA = (BluetoothAdapter) getApplicationContext().getSystemService(TELEPHONY_SERVICE); //what? telephony_service
                if (enabled == true){
                        BA.enable();
                }
                else {
                        BA.disable();
                }
        //android.permission.BLUETOOTH_ADMIN
        }
        
        private void changeWifi (boolean enabled) {
                WifiManager WM = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                WM.setWifiEnabled(enabled);
        }
        
        private void changeVolume (int volume) {
                AudioManager AM = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
                AM.setStreamVolume(AudioManager.STREAM_RING, volume, 0);        
        }
}